import React, { useEffect, useMemo, useState, forwardRef, useImperativeHandle } from 'react';
import {
  AppstoreOutlined,
  BarChartOutlined,
  CloudOutlined,
  ShopOutlined,
  TeamOutlined,
  UploadOutlined,
  UserOutlined,
  VideoCameraOutlined,
} from '@ant-design/icons';
import { Layout, Menu, theme } from 'antd';
import microApp from '@micro-zoe/micro-app'
import { CloseCircleOutlined } from '@ant-design/icons';
import styled from 'styled-components';
import { useSearchParams } from '@/router/hooks';
const { Header, Content, Footer, Sider } = Layout;
const siderStyle = {
  overflow: 'auto',
  height: '100vh',
  position: 'sticky',
  insetInlineStart: 0,
  top: 0,
  bottom: 0,
  scrollbarWidth: 'thin',
  scrollbarGutter: 'stable',
};

const CloseBtn = styled.span`
position: absolute;
right: 0;
top: 0;
padding: 0 6px;
transition: all .3s;
color: #ffffff;
opacity: .5;
&:hover {
  opacity: 1;
  transform: scale(1.2);
}
`

const items = [
  UserOutlined,
  VideoCameraOutlined,
  UploadOutlined,
  BarChartOutlined,
  CloudOutlined,
  AppstoreOutlined,
  TeamOutlined,
  ShopOutlined,
].map((icon, index) => ({
  key: String(index + 1),
  icon: React.createElement(icon),
  label: `nav ${index + 1}`,
}));
const IntegratedPage = (props, ref) => {
  const [menus, setMenus] = useState(localStorage.getItem('micro-app-menus') ? JSON.parse(localStorage.getItem('micro-app-menus')) : [])
  const [activeData, setActiveData] = useState()
  const [cacheCode, setCacheCode] = useState([])
  const searchPrams = useSearchParams()

  useImperativeHandle(ref, () => ({
    setMicroApp: (data) => {
      setMicroApp(data)
    },
    onByTargetMessage: ({ message, target }) => {
    },
    onToAllMessage: (data) => {
    }
  }));
  useEffect(() => {
    setMicroApp(props.screenData)
  }, [props.screenData])

  useEffect(() => {
    searchPrams.forEach((value, key) => {
      if (key.includes('micro-app--')) {
        menus.forEach(d => {
          if (d.code === key.replace('micro-app--', '')) {
            setMicroApp(d)
          }
        })
      }
    })
  }, [])

  const setMicroApp = (data) => {
    if (!data) return
    let options = [...menus]
    let isData = options.find(d => d.code === data.code)
    if (isData) {
      isData.isCache = true
      // menus.splice(menus.indexOf(isData), 1, {...isData, isCache: true})
      setActiveData(isData)

      setMenus(options)
      localStorage.setItem('micro-app-menus', JSON.stringify(options))
    } else {
      localStorage.setItem('micro-app-menus', JSON.stringify([...options, data]))
      setMenus([...options, { ...data, isCache: true }])
      setActiveData(data)
    }
  }

  const menuOpts = useMemo(() => {
    return menus.map((d) => {
      return {
        key: d.code,
        url: d.url,
        label: <>{d.name}<CloseBtn style={{ display: d.isCache ? 'block' : 'none' }} onClick={(e) => unapp(e, d)}><CloseCircleOutlined /></CloseBtn></>,
      }
    })
  }, [menus, activeData])


  const menuSelect = (e) => {
    let data = menus.find(d => d.code === e.key)
    setActiveData(data)
  }
  const unapp = (e, data) => {
    e.stopPropagation()
    let options = [...menus]
    let index = menus.findIndex(d => d.code === data.code)
    options.splice(index, 1)
    microApp.unmountApp('micro-app--' + data.code).then(() => console.log('卸载成功'))
    setMenus(options)
    localStorage.setItem('micro-app-menus', JSON.stringify(options))
    if (options.length && activeData && activeData.code === data.code) {
      setMicroApp(options[index])
    }
    if (!options.length) {
      setActiveData(null)
      props.onClose()
    }
  }

  return (
    <Layout hasSider>
      <Sider style={siderStyle}>
        <div className="demo-logo-vertical" />
        <Menu style={{ minHeight: '100%' }} selectedKeys={activeData ? [activeData.code] : []} mode="inline" items={menuOpts} onSelect={menuSelect} />
      </Sider>
      <Layout>
        <div style={{ height: '100vh' }}>
          {!!activeData && <micro-app name={'micro-app--' + activeData.code} url={activeData.url} clear-data iframe></micro-app>}
        </div>
      </Layout>
    </Layout>
  );
};
export default forwardRef(IntegratedPage);